<?php
/**
 * Created by PhpStorm
 * User: lcz
 * Date: 2019/11/20
 * Time: 9:55
 */

namespace app\common\service;

use app\common\model\AgentAdmin;
use app\common\model\AgentShop;
use app\common\model\PostMan;
use app\common\model\User;
use think\Db;

class UserService {
	
	
	/**
	 * 获取推荐人用户数据
	 * @param $userId 推荐人用户ID
	 * @return int|string
	 * @throws \think\Exception
	 */
	public static function getFansNumById($userId) {
		return \think\Db::name('user')
			->where(['recommend_user_id' => $userId])
			->count();
	}
	
	/**
	 * 获取代理或管理员的代理ID
	 * @param $userId
	 * @return bool
	 * @throws \think\exception\DbException
	 */
	public static function getUserAgentId($userId) {
		$agent = AgentShop::get(['user_id' => $userId]);
		
		if($agent) {
			//如果是代理且状态正常返回代理ID
			return $agent['status'] == AgentShop::STATUS_Y ? $agent['id'] : false;
		}
		
		//查找是否管理员
		$admin = AgentAdmin::get(['user_id' => $userId, 'status' => AgentAdmin::STATUS_NORMAL]);
		if($admin) {
			return $admin['agent_id'];
		}
		return false;
	}
	
	
	/**
	 * 根据用户集合统计粉丝数量
	 * @param $userIds
	 * @return int|string
	 * @throws \think\Exception
	 */
	public static function getFansNumberByUserIds($userIds) {
		return \think\Db::name('user')
			->where(['recommend_user_id' => ['in', $userIds]])
			->count();
	}
	
	/**
	 * 绑定推荐人
	 * @param $userId
	 * @param $recommendUserId
	 * @return bool
	 * @throws \think\exception\DbException
	 */
	public static function bindRecommendUserId($userId, $recommendUserId) {
		$user = User::get($userId);
		if($user && !$user['recommend_user_id']) {
			$recommend = \app\admin\model\User::get($recommendUserId);
			if(!$recommend || $recommend['level'] == 0) {
				return true;
			}
			
			$res = (new User())->save(
				[
					'recommend_user_id' => $recommendUserId,
					'area' => $recommend['area']
				],
				['id' => $userId]);
			
			if(!$res) {
				return false;
			}
		}
		
		return true;
	}
}
